package com.wang.proxy;


import com.wang.annotation.RpcService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;

/**
 * rpc bean初始化
 */
@Component
public class RpcBeanProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //如果是controller
        if (bean.getClass().isAnnotationPresent(RestController.class)) {
            Field[] fields = bean.getClass().getDeclaredFields();
            for (Field field : fields) {
                //查找有rpcService注解的属性
                if (field.isAnnotationPresent(RpcService.class)) {
                    try {
                        //创建代理类
                        RpcClientProxy rpcClientProxy = new RpcClientProxy();
                        Object proxy = rpcClientProxy.createProxy(field.getType());
                        field.setAccessible(true);
                        //注入rpc服务代理类
                        field.set(bean, proxy);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return bean;
    }
}
